﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Com.CloudTalk.Controller;
using System.Diagnostics;
using System.Collections;
using System.Threading;
using System.Collections.Specialized;

namespace WebApplication.Controllers
{
    public class HomeController : AsyncController
    {
        private static StringDictionary clientRooms = new StringDictionary();

        static HomeController()
        {
            clientRooms.Add("Galeazi", "Galeazi Chat Room");
            clientRooms.Add("PoaClinicas", "PoaClinicas Chat Room");
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ChatIndexWithParam(string client, string data)
        {
            if (!clientRooms.ContainsKey(client))
            {
                throw new ArgumentException();
            }

            if (String.IsNullOrEmpty(data) ||
                data != "Host")
            {
                return ChatIndex(client);
            }
            
            ViewData["RoomName"] = clientRooms[client];
            return View("ChatIndex");
        }

        public ActionResult ChatIndex(string client)
        {
            if (!clientRooms.ContainsKey(client))
            {
                throw new ArgumentException();
            }

            string sRoomName = clientRooms[client];
            CTChatRoom theRoom = CloudTalkController.OpenChatRoom(sRoomName);

            ViewData["Online"] = (theRoom.ClientList.Count > 0);
            ViewData["RoomName"] = sRoomName;

            return View();
        }

        public ActionResult RoomStatus(string id)
        {
            if (!clientRooms.ContainsKey(id))
            {
                throw new ArgumentException();
            }

            string sRoomName = clientRooms[id];
            CTChatRoom theRoom = CloudTalkController.OpenChatRoom(sRoomName);

            return Json(new { online = (theRoom.ClientList.Count > 0) }, "text/html", JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult LeaveRoom()
        {
            string sClientEmail = Request.QueryString["email"];
            string sRoomName = Request.QueryString["room"];

            if (String.IsNullOrEmpty(sClientEmail) ||
                String.IsNullOrEmpty(sRoomName))
            {
                throw new ArgumentNullException();
            }

            if (CloudTalkController.GetClientByEmail(sClientEmail) == null)
            {
                throw new InvalidOperationException();
            }

            CTChatRoom theRoom = CloudTalkController.OpenChatRoom(sRoomName);
            CTClient clientLeaving = CloudTalkController.GetClientByEmail(sClientEmail);

            CloudTalkController.RemoveClient(theRoom, clientLeaving);

            return PartialView();
        }

        [HttpPost]
        public ActionResult JoinRoom()
        {
            string sClientName = Request.Form["Name"];
            string sClientEmail = Request.Form["Email"];
            string sRoomName = Request.Form["RoomName"];

            if (String.IsNullOrEmpty(sClientName) ||
                String.IsNullOrEmpty(sClientEmail))
            {
                // invalid arguments
                return Json(new { Code = 0, Message = "Nome ou email inválido." });
            }

            ViewData["ClientName"] = sClientName;
            ViewData["ClientEmail"] = sClientEmail;

            // Allow users to come back later
            /*if (CloudTalkController.GetClientByEmail(sClientEmail) != null)
            {
                return Json(new { Code = 0, Message = "O email escolhido já está em uso." });
            }*/

            CTChatRoom theRoom = CloudTalkController.OpenChatRoom(sRoomName);
            CTClient newClient;

            try
            {
                newClient = CloudTalkController.AddClient(
                    theRoom,
                    sClientName,
                    sClientEmail,
                    RoleTypes.Member);
            }
            catch (FullChatRoomException e)
            {
                return Json(new { Code = 3, Message = e.Message, Position = e.QueueSize });
            }
            catch (DuplicateRoomMemberException e)
            {
                return Json(new { Code = 0, Message = e.Message });
            }

            // success
            return Json(new { Code = 1, Message = "Sucesso ao entrar na sala." });
        }

        public ActionResult OneToOne()
        {
            return View();
        }

        public ActionResult Many()
        {
            return View();
        }

        public void EventsAsync()
        {
            string sClientEmail = Request.QueryString["email"];

            if(String.IsNullOrEmpty(sClientEmail))
            {
                throw new ArgumentNullException();
            }

            AsyncManager.OutstandingOperations.Increment();

            EventsService eventsService = new EventsService();
            eventsService.GetMessagesCompleted += (sender, e) =>
            {
                AsyncManager.Parameters["events"] = e.Messages;
                AsyncManager.OutstandingOperations.Decrement();
            };
            eventsService.GetEventsAsync(sClientEmail);

        }

        public ActionResult EventsCompleted(object[] events)
        {
            return Json(
                events,
                JsonRequestBehavior.AllowGet);
        }

        private object[] GetMembers(string _sRoomName)
        {
            CTChatRoom testRoom = CloudTalkController.OpenChatRoom(_sRoomName);
            List<object> lstJson = new List<object>();

            testRoom.ClientList
                .Select(c => c.Name)
                .ToList()
                .ForEach(c =>
            {
                lstJson.Add(new { Name = c });
            });

            return lstJson.ToArray();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SendMessage(FormCollection vars)
        {
            string sMessage = vars["Message"];
            string sClientEmail = vars["ClientEmail"];
            string sRoomName = vars["RoomName"];

            if (String.IsNullOrEmpty(sMessage) ||
                String.IsNullOrEmpty(sClientEmail) ||
                String.IsNullOrEmpty(sRoomName))
            {
                throw new ArgumentNullException();
            }

            CTClient c = CloudTalkController.GetClientByEmail(sClientEmail);

            if (c == null)
            {
                throw new InvalidOperationException();
            }

            Thread t = new Thread(new ThreadStart(delegate
            {
                CTChatRoom testRoom = CloudTalkController.OpenChatRoom(sRoomName);
                CloudTalkController.SendMessage(c, sMessage, testRoom);
            }));

            t.Start();

            return PartialView();
        }

        [HttpPost]
        public ActionResult ClearRoom(FormCollection vars)
        {
            string sRoomName = vars["RoomName"];

            if (String.IsNullOrEmpty(sRoomName))
            {
                throw new ArgumentNullException();
            }

            CTChatRoom testRoom = CloudTalkController.OpenChatRoom(sRoomName);
            CloudTalkController.ClearClients(testRoom);

            return PartialView();
        }
    }
}
